﻿using Mapster;
using RsCms.Application.Posts.Dto;
using RsCms.Core;
using RsCode;

namespace RsCms.Application.Pages
{
    public class PagesAppSerivce:IPagesAppService
    {
        IPostsRepository postRepository;
        IPageDomainService pageDomainService;
        public PagesAppSerivce(IPageDomainService pageDomainService, IPostsRepository postRepository)
        {
            this.pageDomainService = pageDomainService;
            this.postRepository = postRepository;

        }

        public async Task<PostsDto> GetPageInfoAsync(string id)
        {
            var info=await pageDomainService.GetPageInfoAsync(id);
            var target= info?.Adapt<PostsDto>()??new PostsDto();
            HtmlDecode(target);
            return target;
        }

        public async Task<PostEditDto> SaveAsync(PostEditDto dto)
        {
            HtmlEncode(dto);
            var info = dto.MapTo<Entities.Posts>();
            var m= await pageDomainService.SaveAsync(info);
            var target= m.Adapt<PostEditDto>();

            HtmlDecode(target);
            return target;
        }

        public async Task<PageData<PostEditDto>> PageAsync(int page,int pageSize)
        {
            var info=await pageDomainService.PageAsync(page,pageSize);
            return info?.Adapt<PageData<PostEditDto>>() ?? new PageData<PostEditDto>();
        }

        public Task DeleteAsync(string id)
        {
            postRepository.PostStore.Delete(x => x.Id == id);
            return Task.CompletedTask;
        }

        void HtmlEncode(PostEditDto posts)
        {
            if (!string.IsNullOrWhiteSpace(posts.Title))
                posts.Title = System.Web.HttpUtility.HtmlEncode(posts.Title);
            if (!string.IsNullOrWhiteSpace(posts.Markdown))
                posts.Markdown = System.Web.HttpUtility.HtmlEncode(posts.Markdown);
        }
        void HtmlDecode(PostsDto posts)
        {
            if (!string.IsNullOrWhiteSpace(posts.Title))
                posts.Title = System.Web.HttpUtility.HtmlDecode(posts.Title);
            if (!string.IsNullOrWhiteSpace(posts.Markdown))
                posts.Markdown = System.Web.HttpUtility.HtmlDecode(posts.Markdown);
        }
        void HtmlDecode(PostEditDto posts)
        {
            if (!string.IsNullOrWhiteSpace(posts.Title))
                posts.Title = System.Web.HttpUtility.HtmlDecode(posts.Title);
            if (!string.IsNullOrWhiteSpace(posts.Markdown))
                posts.Markdown = System.Web.HttpUtility.HtmlDecode(posts.Markdown);
        }

    }
}
